import cn.edu.dgut.infomation.LoginFlag;
import cn.edu.dgut.infomation.UserInfo;
import cn.edu.dgut.infomation.httpClientTool;
import org.apache.http.message.BasicNameValuePair;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * loginServlet是用来验证莞工中央登录的
 * 用来请求open_id和用户信息，并储存isLogin(session)中
 */

@WebServlet("/login/dgut")
public class loginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String token = request.getParameter("token");
        String appid = "javaee";
        String appsecret = "b3b52e43ccfd";
        String userip = request.getRemoteAddr();     //获取本地ip

        String url = "https://cas.dgut.edu.cn/ssoapi/v2/checkToken";
        // 创建checkToken的参数列表
        List<BasicNameValuePair> paramList = new ArrayList<>();
        paramList.add(new BasicNameValuePair("token",token));
        paramList.add(new BasicNameValuePair("appid",appid));
        paramList.add(new BasicNameValuePair("appsecret",appsecret));
        paramList.add(new BasicNameValuePair("userip",userip));

        //封装了一个httpClient工具类
        httpClientTool client = new httpClientTool();
        String resultString = client.getPostInfo(url,paramList,response);
        Jsonb jsonb = JsonbBuilder.create();
        LoginFlag loginFlag = jsonb.fromJson(resultString,LoginFlag.class);
        if(Integer.parseInt(loginFlag.getError())!=0){
            //token不合法，退出
            response.getWriter().println(resultString);
            return;
        }else {
            String access_token = loginFlag.getAccess_token();
            String openid = loginFlag.getOpenid();
            url = "https://cas.dgut.edu.cn/oauth/getUserInfo";
            // 创建getUserInfo的参数列表
            paramList = new ArrayList<>();
            paramList.add(new BasicNameValuePair("access_token", access_token));
            paramList.add(new BasicNameValuePair("openid", openid));
            resultString = client.getPostInfo(url, paramList, response);
            UserInfo user = jsonb.fromJson(resultString, UserInfo.class);

            if(user.getError()!=null){
                //access-token不合法，退出
                response.getWriter().println(resultString);
                return;
            }

            Map<String, String> info = new HashMap<String, String>();
            info.put("username", user.getUsername());
            info.put("name", user.getName());
            info.put("faculty_title", user.getFaculty_title());
            info.put("group", user.getGroup());
            info.put("openid", user.getOpenid());
            info.put("wx_openid", user.getWx_openid());
            info.put("faculty", user.getFaculty());
            HttpSession session = request.getSession(true);
            session.setAttribute("isLogin", info);
            response.sendRedirect("/index.jsp");
        }
    }
}
